<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="roleDialogVisible = true"
            >添加角色</el-button
          ></el-col
        >
      </el-row>
      <el-table :data="roleList" stripe border>
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              :class="['bdbottom', index1 === 0 ? 'bdtop' : '']"
              v-for="(item1, index1) in scope.row.children"
              :key="index1"
              class="vcenter"
            >
              <el-col :span="5">
                <el-tag closable @close="removeTagById(scope.row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="[index2 !== 0 ? 'bdtop' : '']"
                  v-for="(item2, index2) in item1.children"
                  :key="index2"
                  class="vcenter"
                >
                  <el-col :span="5">
                    <el-tag
                      closable
                      @close="removeTagById(scope.row, item2.id)"
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19">
                    <el-tag
                      v-for="(item3, index3) in item2.children"
                      :key="index3"
                      type="warning"
                      closable
                      @close="removeTagById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="roleSelectChange(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="roleDelete(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setDefaultKeys"
    >
      <el-tree
        show-checkbox
        default-expand-all
        :default-checked-keys="defualtKeys"
        node-key="id"
        :data="rightsList"
        :props="treeProps"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="添加角色"
      :visible.sync="roleDialogVisible"
      width="50%"
      @close="roleAddChange()"
    >
      <el-form
        :model="roleForm"
        :rules="roleRule"
        ref="roleRuleAddForm"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleAdd()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="编辑角色"
      :visible.sync="roleChangeDialogVisible"
      width="50%"
      @close="roleSelectChangeClose()"
    >
      <el-form
        :model="roleForm"
        :rules="roleRule"
        ref="roleRuleForm"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleChangeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleChange()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleDialogVisible: false,
      roleRule: {
        roleName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 0, max: 10, message: '长度在 0 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },
      roleForm: { roleName: '', roleDesc: '' },
      roleId: 0,
      defualtKeys: [],
      setRightDialogVisible: false,
      roleList: [],
      rightsList: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      roleChangeDialogVisible: false
    }
  },
  methods: {
    async roleSelectChange(id) {
      this.roleId = id
      const { data } = await this.$http.get('roles/' + id)
      if (data.meta.status !== 200) {
        return this.$message.error('获取角色失败')
      }
      this.roleForm = data.data
      this.roleChangeDialogVisible = true
    },
    async roleChange() {
      const { data } = await this.$http.put(
        'roles/' + this.roleId,
        this.roleForm
      )
      if (data.meta.status !== 200) {
        return this.$message.error('更改角色失败')
      }

      this.$message.success('更改角色成功')
      this.getRoleList()

      this.roleChangeDialogVisible = false
    },
    roleAddChange() {
      this.roleForm = { roleName: '', roleDesc: '' }
      this.$refs.roleRuleAddForm.resetFields()
    },
    roleSelectChangeClose() {
      this.roleForm = { roleName: '', roleDesc: '' }
      this.$refs.roleRuleForm.resetFields()
    },
    roleDelete(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data } = await this.$http.delete('roles/' + id)
          if (data.meta.status !== 200) {
            return this.$message.error('删除角色失败')
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getRoleList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async roleAdd() {
      this.$refs.roleRuleAddForm.validate(async valid => {
        if (valid) {
          const { data } = await this.$http.post('roles', this.roleForm)
          this.$message.success('添加角色成功')
          if (data.meta.status !== 201) {
            return this.$message.error('添加角色失败')
          }
          this.getRoleList()
        } else {
          return this.$message.err('完善信息格式')
        }
        this.roleDialogVisible = false
      })
    },
    async allotRight() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const keysStr = keys.join(',')
      const { data } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: keysStr
      })
      if (data.meta.status !== 200) {
        return this.$message.error('更改权限失败')
      }
      this.getRoleList()
      this.setRightDialogVisible = false
    },
    setDefaultKeys() {
      this.defualtKeys = []
    },
    async showRightDialog(node) {
      this.roleId = node.id
      const { data } = await this.$http.get('rights/tree')
      if (data.meta.status !== 200) {
        return this.$message.error('获取权限失败')
      }
      this.rightsList = data.data

      this.getLeafKeys(node, this.defualtKeys)
      this.setRightDialogVisible = !this.setRightDialogVisible
    },
    removeTagById(role, id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data } = await this.$http.delete(
            'roles/' + role.id + '/rights/' + id
          )
          if (data.meta.status !== 200) {
            return this.$message.error('删除权限失败')
          }
          role.children = data.data
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    async getRoleList() {
      const { data } = await this.$http.get('roles')
      if (data.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.roleList = data.data
    },
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(node => {
        this.getLeafKeys(node, arr)
      })
    }
  },
  created() {
    this.getRoleList()
  }
}
</script>
<style lang="less" scoped>
.vcenter {
  display: flex;
  align-items: center;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>
